package com.wzy.controller;

import com.wzy.entity.Address;
import com.wzy.entity.PageBean;
import com.wzy.entity.ResultInfo;
import com.wzy.entity.User;
import com.wzy.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private HttpSession session;

    @Autowired
    private AddressService addressService;
    /**
     * 写个通用的方法，从会话域中获取用户对象
     */
    protected User getUserFromSession(){
        return (User)session.getAttribute("user");
    }
    /**
     * 查询1页数据
     * @param params 封装了current和size等多个参数
     */
    @RequestMapping("/findPage")
    public PageBean<Address> findPage(@RequestBody Map<String,Object> params){
        //1.获取current和size的值
        int current = (int) params.get("current");
        int size = (int) params.get("size");
        //2.调用业务层获取PageBean对象
        User user = getUserFromSession();
        //uid从会话域中获取
        PageBean<Address> pageBean = addressService.findAddress(current, size, user.getUid());
        return pageBean;
    }

    /**
     * 添加一个用户
     */
    @RequestMapping("/save")
    public ResultInfo save(@RequestBody Address address){
        //从会话域中获取用户对象
        User user = getUserFromSession();
        //设置address的uid的值
        address.setUid(user.getUid());
        //调用业务层写入地址信息
        addressService.save(address);
        //返回添加成功
        return new ResultInfo(true,"成功添加收获地址");
    }

    @RequestMapping("/update")
    public ResultInfo update(@RequestBody Address address){
        addressService.update(address);
        return new ResultInfo(true,"成功修改收获地址");
    }

    /**
     * 修改默认的收货地址
     */
    @RequestMapping("/changeDefaultAddress")
    public ResultInfo changeDefaultAddress(Integer aid){
        //从会话域中获取uid的值
        User user = getUserFromSession();
        addressService.changeDefaultAddress(user.getUid(),aid);
        return new ResultInfo(true,"成功修改默认收货地址");
    }

    @RequestMapping("/delete")
    public ResultInfo delete(Integer aid){
        addressService.delete(aid);
        return new ResultInfo(true);
    }
}
